﻿using System;

using System.Collections.Generic;
using System.Text;
using Silvermoon.UI;
using Silvermoon.Windows;

namespace Silvermoon.Controls
{
    /// <summary>
    /// Abstact Item which supports IsPressed.
    /// </summary>
    public abstract class VirtualItem : Item
    {
        protected RotateTransform rotation;


        public static readonly PropertyAccessor<VirtualItem, float> YRotationProperty = PropertyAccessor.Register<VirtualItem, float>(
            "YRotation",
            (c) => c.rotation.Angle,
            (c, v) => { c.rotation.Angle = v; c.Invalidate(InvalidationFlag.Transformation); });

        static VirtualItem()
        {
            VisualStateManager.RegisterClassManager(typeof(VirtualItem), ItemStateManagers.ItemManager);
        }

        public VirtualItem()
            : base()
        {
            rotation = new RotateTransform { Axis = RotateAxis.YAxis, OrigX = 1f };
            Transformation += rotation;
        }

        protected override void Dispose(bool dispose)
        {
            base.Dispose(dispose);
        }

        public bool IsPressed
        {
            get { return (bitmask & IS_PRESSED_BIT) != 0; }
            set
            {
                if (IsReadonly) value = false;
                if (IsPressed != value)
                {
                    bitmask = value ? bitmask | IS_PRESSED_BIT : bitmask & ~IS_PRESSED_BIT;
                    Invalidate(InvalidationFlag.LayoutAppearance);
                    OnPressedChanged();
                }
            }
        }



        protected internal override void OnTouchDown(TouchEventArgs e)
        {
            if (!e.Handled && !IsReadonly)
            {
                IsPressed = true;
            }
            base.OnTouchDown(e);
            e.Handled = true;
        }


        protected internal override void OnTouchUp(TouchEventArgs e)
        {
            IsPressed = false;
            base.OnTouchUp(e);
            e.Handled = true;
        }

        protected internal override void OnTap(TapEventArgs e)
        {
            bool handled = e.Handled;
            if (!handled)
            {
                ICommand cmd = Command;
                if (cmd != null) RaiseCommand(cmd);
            }
            base.OnTap(e);
        }

        protected virtual void OnPressedChanged()
        {
            SetState(IsPressed ? VState.Pressed : VState.Normal);
        }

    }
}
